﻿Imports System.Collections.Generic
Imports EnvDTE
Imports System.Linq
Imports EnvDTE80

Public Class LinkByProjectNameProvider
  Inherits BaseProvider

  Public Class LinkByProjectNameSettings
    Public Property RemoveNonSourceLinks As Boolean
  End Class

  Public Overrides Sub Run(app As DTE2)

    Dim phs = ExtractProjectHolders(app.Solution.Projects)
    phs.Sort()

    Dim sourceProjects As ProjectHolderCollection = SelectMultipleProjects(phs, "Select source projects:")
    If sourceProjects Is Nothing OrElse sourceProjects.Count = 0 Then Return

    Dim dict As Dictionary(Of ProjectHolder, ProjectHolderCollection) = _
      GenerateDictionaryOfSourceToTargetProjectMappings(sourceProjects, phs)

    Dim sett = GetCopyProviderSettings()

    Dim resultDataSet As New List(Of ResultItem)
    For Each fKey In dict.Keys
      Dim xSrc = fKey
      Dim xTrg = dict.Item(fKey)
      Dim resPom = CopyProvider.DoLinking(xSrc, xTrg, sett)
      resultDataSet.AddRange(resPom)
    Next

    Dim f As New FrmResults
    f.SetResultDataSet(resultDataSet)
    f.Show()

  End Sub

  Private Function GenerateDictionaryOfSourceToTargetProjectMappings( _
                                                                    sourceProjects As ProjectHolderCollection, phs As ProjectHolderCollection) _
                                                                  As Dictionary(Of ProjectHolder, ProjectHolderCollection)
    Dim ret As New Dictionary(Of ProjectHolder, ProjectHolderCollection)

    For Each fProject In sourceProjects

      Dim projLocal = fProject
      Dim pom = phs.Where(Function(x) x.Project.Name = projLocal.Project.Name And Not x.Project Is projLocal.Project)
      Dim lphc = New ProjectHolderCollection()
      lphc.AddRange(pom)

      ret.Add(fProject, lphc)

    Next

    Return ret
  End Function

  

End Class
